#!/usr/bin/env bash
source "$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")/config"
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_BASE_PATH/common/functions"
source "$(dirname "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)")/functions"

service-promote-cmd() {
  #E if you have a $PLUGIN_COMMAND_PREFIX service linked to an app and try to link another $PLUGIN_COMMAND_PREFIX service
  #E another link environment variable will be generated automatically:
  #E
  #E     DOKKU_${PLUGIN_DEFAULT_ALIAS}_BLUE_URL=${PLUGIN_SCHEME}://other_service:ANOTHER_PASSWORD@dokku-${PLUGIN_COMMAND_PREFIX}-other-service:${PLUGIN_DATASTORE_PORTS[0]}/other_service
  #E
  #E you can promote the new service to be the primary one
  #E > NOTE: this will restart your app
  #E dokku $PLUGIN_COMMAND_PREFIX:promote other_service playground
  #E this will replace ${PLUGIN_DEFAULT_ALIAS}_URL with the url from other_service and generate
  #E another environment variable to hold the previous value if necessary.
  #E you could end up with the following for example:
  #E
  #E     ${PLUGIN_DEFAULT_ALIAS}_URL=${PLUGIN_SCHEME}://other_service:ANOTHER_PASSWORD@dokku-${PLUGIN_COMMAND_PREFIX}-other-service:${PLUGIN_DATASTORE_PORTS[0]}/other_service
  #E     DOKKU_${PLUGIN_DEFAULT_ALIAS}_BLUE_URL=${PLUGIN_SCHEME}://other_service:ANOTHER_PASSWORD@dokku-${PLUGIN_COMMAND_PREFIX}-other-service:${PLUGIN_DATASTORE_PORTS[0]}/other_service
  #E     DOKKU_${PLUGIN_DEFAULT_ALIAS}_SILVER_URL=${PLUGIN_SCHEME}://lolipop:SOME_PASSWORD@dokku-${PLUGIN_COMMAND_PREFIX}-lolipop:${PLUGIN_DATASTORE_PORTS[0]}/lolipop
  #A service, service to run command against
  #A app, app to run command against
  declare desc="promote service <service> as ${PLUGIN_DEFAULT_ALIAS}_URL in <app>"
  local cmd="$PLUGIN_COMMAND_PREFIX:promote" argv=("$@")
  [[ ${argv[0]} == "$cmd" ]] && shift 1
  declare SERVICE="$1" APP="$2"
  APP=${APP:="$DOKKU_APP_NAME"}

  [[ -z "$SERVICE" ]] && dokku_log_fail "Please specify a valid name for the service"
  [[ -z "$APP" ]] && dokku_log_fail "Please specify an app to run the command on"
  verify_service_name "$SERVICE"
  verify_app_name "$APP"
  service_promote "$SERVICE" "$APP"
}

service-promote-cmd "$@"
